/*
@Copyright:LintCode
@Author:   tjyemail
@Problem:  http://www.lintcode.com/problem/balanced-binary-tree
@Language: C++
@Datetime: 16-02-09 05:42
*/

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
    int getdepth(TreeNode *r){
        if (r==NULL)
            return 0;
        int left = getdepth(r->left);
        int right = getdepth(r->right);
        return left<right?right+1:left+1;
    }
public:
    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
    bool isBalanced(TreeNode *root) {
        // write your code here
        if (root==NULL)
            return true;
        int left = getdepth(root->left);
        int right = getdepth(root->right);
        if (left-right<-1 || left-right>1)
            return false;
        return isBalanced(root->left) && isBalanced(root->right);
    }
};